package com.chenglu.android.common.net;


import androidx.annotation.NonNull;


import com.chenglu.android.BuildConfig;
import com.chenglu.android.common.utils.SPUtils;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava3.RxJava3CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * * @author: lyj
 *  @Created: by Copyright 2023/3/6 Guangzhou Hongma Technology Co., Ltd. All rights reserved.
 * description：retrofit单列
 *
 *
 */
public class RetrofitClient {

    private static volatile RetrofitClient instance;
    private APIService apiService;
//    http://192.168.254.244:9080/idc
//    public String baseUrl = "http://47.115.160.226:18038";
    public String baseUrl = Constant.BASEDEVAPI;



    private Retrofit retrofit;
    private OkHttpClient okHttpClient;


    private RetrofitClient() {
    }

    public static RetrofitClient getInstance() {
        if (instance == null) {
            synchronized (RetrofitClient.class) {
                if (instance == null) {
                    instance = new RetrofitClient();
                }
            }
        }
        return instance;
    }

    /**
     * 设置Header
     *
     * @return
     */
    private Interceptor getHeaderInterceptor() {
        return new Interceptor() {
            @Override
            public Response intercept(@NonNull Chain chain) throws IOException {
                Request original = chain.request();
                Request.Builder requestBuilder = original.newBuilder();
//                        .addHeader("User-Type","wap")
//                        .addHeader("Authorization","d2FwOlZPclVUOVVB");
                //添加Token 请求头

                Request request = requestBuilder.build();
                return chain.proceed(request);
            }
        };

    }


    /**
     * 设置拦截器 打印日志
     *
     * @return
     */
    private Interceptor getInterceptor() {

        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        //显示日志
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        return interceptor;
    }

    public OkHttpClient getOkHttpClient() {
        if (okHttpClient == null) {
            //如果为DEBUG 就打印日志
            if (BuildConfig.DEBUG) {
                okHttpClient = new OkHttpClient().newBuilder()
                        //设置Header
                        .addInterceptor(getHeaderInterceptor())
                        //设置拦截器
                        .addInterceptor(getInterceptor())
                        .build();
            } else {
                okHttpClient = new OkHttpClient().newBuilder()
                        //设置Header
                        .addInterceptor(getHeaderInterceptor())
                        //设置连接超时时间
                        .connectTimeout(30, TimeUnit.SECONDS)
                        .build();
            }

        }

        return okHttpClient;
    }

    public APIService getApi() {
        //初始化一个client,不然retrofit会自己默认添加一个
        if (retrofit == null) {
            retrofit = new Retrofit.Builder()
                    //设置网络请求的Url地址
                    .baseUrl(baseUrl)
                    //设置数据解析器
                    .addConverterFactory(GsonConverterFactory.create())
                    //设置网络请求适配器，使其支持RxJava与RxAndroid
                    .addCallAdapterFactory(RxJava3CallAdapterFactory.create())
                    .client(getOkHttpClient())
                    .build();
        }
        //创建—— 网络请求接口—— 实例
        if (apiService==null){
            apiService = retrofit.create(APIService.class);
        }

        return apiService;
    }



    public OkHttpClient getOkHttpClient1() {
        if (okHttpClient == null) {
            //如果为DEBUG 就打印日志
            if (BuildConfig.DEBUG) {
                okHttpClient = new OkHttpClient().newBuilder()
                        //设置Header
                        .addInterceptor(getHeaderInterceptor())
                        //设置拦截器
                        .addInterceptor(getInterceptor())
                        .build();
            } else {
                okHttpClient = new OkHttpClient.Builder()
                        .retryOnConnectionFailure(true)
                        .connectTimeout(15, TimeUnit.SECONDS)
                        .addInterceptor(initOkHttpInterceptor())
                        .build();

            }

        }

        return okHttpClient;
    }
    //设置拦截器
    private  Interceptor initOkHttpInterceptor() {
        Interceptor mTokenInterceptor = new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request originalRequest = chain.request();
               String token =  SPUtils.getString("AaccessToken","null");
                if ( token == null) {//表示第一次登陆还没拉取过token
                    return chain.proceed(originalRequest);//执行登陆的操作
                }
                //此处表示已有token 这时只需要判断401即可
                Request authorised = originalRequest.newBuilder()
                        .header("Authorization",  token)//此处的token 是你保存在本地的
                        .build();
                Response response = chain.proceed(authorised);//执行此次请求
                if (response.code() == 401) {//返回为token失效
//                    refreshToken();//重新获取token，此处的刷新token需要同步执行以防止异步到来的问题
                    Request newRequest = originalRequest.newBuilder()
                            .header("Authorization", token)
                            .build();//
                    return chain.proceed(newRequest);
                }
                return response;
            }
        };


        return  mTokenInterceptor;

    }




}
